/**
 * @Date: Mar 8, 2010 8:07:06 PM
 */
package com.philip.journal.home.controller.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

import com.philip.journal.common.StringUtils;
import com.philip.journal.core.controller.ResponseHandler;
import com.philip.journal.core.exception.JournalException;
import com.philip.journal.core.service.ServiceProxy;
import com.philip.journal.home.controller.HomeFieldname;

/**
 * For adding Branch.
 *
 * @author cry30
 */
public class AddBranchAction extends AbstractTreeAction {

    /**
     * Default delegate constructor.
     *
     * @param serviceProxy Service proxy to be injected by Spring.
     * @param responseHandler Response handler to be injected by Spring.
     */
    public AddBranchAction(final ServiceProxy serviceProxy, final ResponseHandler responseHandler) {
        super(serviceProxy, responseHandler);
    }

    @Override
    public void execute() throws ServletException, IOException {
        final String parent = getHttpServletRequest().getParameter(PARENT_ID);
        String branchName = getHttpServletRequest().getParameter(BRANCH_NAME);
        branchName = getStringUtils().removeHtmlTags(branchName);
        try {
            final long branchId = getServiceProxy().addBranch(parseId(parent), branchName);
            final Map<String, Object> param = new HashMap<String, Object>();
            param.put(HomeFieldname.FIELD_ID, branchId);
            param.put(HomeFieldname.BRANCH_NAME, branchName);
            getResponseHandler().respondSuccess(getHttpServletResponse(), param);
        } catch (final JournalException e) {
            getLogger().debug(e.getMessage(), e);
            getResponseHandler().respondFail(getHttpServletResponse(),
                    e.getCause().getCause().getClass().getSimpleName(),
                    e.getMessage() + getStringUtils().stackTraceToString(e.getCause()));
        }
    }

    StringUtils getStringUtils() {
        return StringUtils.getInstance();
    }

}
